using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.FileProviders;
using Microsoft.OpenApi.Models;
//using Anet.Data;
using MySqlConnector;

using Newtonsoft.Json;

using NLog;
using NLog.Web;

using SManaApi;
using SManaApi.Extensions;

using SManaModel.entities;
using SManaModel.models;

using LogLevel = Microsoft.Extensions.Logging.LogLevel;


var builder = WebApplication.CreateBuilder(args);
IConfiguration configuration = builder.Configuration;
// 自定义配置端口号
//builder.WebHost.UseUrls("http://*:902");


#region 配置管理

// 配置管理器
var host = builder.Host;
var logging = builder.Logging;
#if !DEBUG
var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
host.ConfigureAppConfiguration((h, c) =>
{
    // 根据host配置文件加载端口号
    c.AddJsonFile("host.json", true, true);
});
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
host.UseNLog();
#endif

#endregion

#region 服务配置

// 添加cors
builder.Services.AddCorsService();
// 添加验证
TokenConfig tokenConfig = configuration.GetValue<TokenConfig>("TokenConfig");
builder.Services.AddAuthenticationService(tokenConfig);
// 添加数据库上下文
builder.Services.AddDbContext<MyDbContext>(options =>
    options.UseMySql(builder.Configuration.GetConnectionString("MySQL"), MySqlServerVersion.LatestSupportedServerVersion));
// 添加工程服务
builder.Services.AddProjectServices();
// 添加控制器
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
//添加json格式化
builder.Services.AddMvcCore().AddNewtonsoftJson(options =>
{
    options.SerializerSettings.DateFormatString = "yyyy-MM-dd hh:mm:ss";
    options.SerializerSettings.MissingMemberHandling = MissingMemberHandling.Ignore;
    options.SerializerSettings.NullValueHandling = NullValueHandling.Include;
    options.SerializerSettings.Formatting = Formatting.None;
});
// 添加swagger api测试
builder.Services.AddSwaggerGen(options =>
{
    // 设置请求头部
    options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
    {
        Description = "在下框中输入请求头中需要添加Jwt授权Token：Bearer Token",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        BearerFormat = "JWT",
        Scheme = JwtBearerDefaults.AuthenticationScheme,
    });
    //options.AddSecurityRequirement(new OpenApiSecurityRequirement
    //{
    //    {
    //        new OpenApiSecurityScheme
    //        {
    //            Reference = new OpenApiReference
    //            {
    //                Type = ReferenceType.SecurityScheme,
    //                Id = "Bearer"
    //            }
    //        },
    //        Array.Empty<string>()
    //    }
    //});

    // 获取xml注释文件的目录
    var xmlPath = Path.Combine(AppContext.BaseDirectory, "SManaApi.xml");
    options.IncludeXmlComments(xmlPath, true);
});

#endregion

#region 应用配置

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    //app.UseDeveloperExceptionPage();
    app.UseExceptionHandler("/Home/Error");
}
else
{
    app.UseMiddleware<ExceptionHandlingMiddleware>();
}

app.UseSwagger();
app.UseSwaggerUI();

app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), "./wwwroot/UploadFile")),
    RequestPath = "/static"
});
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

//var pathbase = configuration["PathBase"];
//if (!string.IsNullOrEmpty(pathbase))
//{
//    app.UsePathBase(pathbase);
//}

app.Run();

#endregion